package com.luomo.java.juc.producerconsumer;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LiuMei
 * @date 2021-04-13.
 */
public class BlockQueueShareData extends ShareData {

    //默认开启进行生产+消费
    private volatile boolean FLAG = true;
    private BlockingQueue<String> blockingQueue;
    private AtomicInteger number = new AtomicInteger();

    BlockQueueShareData(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void add() {
        String result;
        boolean offer;
        while (FLAG) {
            try {
                result = number.incrementAndGet()+"";
                offer = blockingQueue.offer(result);
                if (offer) {
                    System.out.println(Thread.currentThread().getName() + "\t生产" + result + "成功");
                } else {
                    System.out.println(Thread.currentThread().getName() + "\t生产失败");
                }
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "\t停止生产");
    }

    @Override
    public void sub() {
        String poll;
        while (FLAG) {
            try {
                poll = blockingQueue.poll(2, TimeUnit.SECONDS);
                if (StrUtil.isBlank(poll)) {
                    FLAG = false;
                    System.out.println(Thread.currentThread().getName() + "\t\t消费退出");
                    return;
                } else {
                    System.out.println(Thread.currentThread().getName() + "\t\t消费" + poll + "成功");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        System.out.println();
        this.FLAG = false;
    }
}
